import re
from random import randint
import rpy2.robjects as robjects

word = re.compile('[\\w\n]')
onlyWords = re.compile('\\w')

class CodeDocument(object):

    def __init__(self):
        self.blocks = []
        self.tmpFiles = []

    def addBlock(self,block):
        if (block != None):
            self.blocks.append(block)

    def toString(self):
        self.output = ""
        self.tmpFiles = []
        for block in self.blocks:
            self.output = self.output + block.toString()+"\n"
            if (len(block.tmpFiles) > 0):
                self.tmpFiles = self.tmpFiles + block.tmpFiles
            
        return self.output

class CodeBlock(object):
    
    def __init__(self,tmpImageBox,template):
        self.code = []
        self.output = ""
        self.dirty = 1
        self.tmpImageBox = tmpImageBox
        self.tmpFiles = []
        self.template = template

    def cleanCode(self):
        if (not onlyWords.search(self.code[0])):
            self.code = self.code[1:len(self.code)]

        if (not onlyWords.search(self.code[len(self.code)-1])):
            self.code = self.code[0:len(self.code)-1]

    def addLine(self,docLine):
        self.code.append(docLine)
        self.dirty = 1;

    def evaluateBlock(self):
        # Evaluate the python expression in the python engine
        self.tmpFiles = []
        if (len(self.code) == 0):
            return
        outputPrimer = '';
        for line in self.code:
            outputPrimer+=line+"<br/>"
            if (line.find('plot(') >= 0): 
                tmpPlot = str(randint(0,100000))+'.jpg'
                self.tmpFiles.append(tmpPlot)
                robjects.r('jpeg(filename=\''+tmpPlot+'\')')
                output = robjects.r(line)
                robjects.r('dev.off()')
                
                outputPrimer += "<img class=\"rGraphic\" src=\""+tmpPlot+"\"/>" 
            else:
                output = robjects.r(line)
                if (line[len(line)-1] != ';'):
                    outputPrimer +="  "+str(output)+"<br/>"
            
        self.output = self.template.replace('{R_insert}',outputPrimer)
        self.dirty = 0

    def toString(self):
        self.cleanCode()
        if (self.dirty):
            self.evaluateBlock()
        return self.output

class CommentBlock(object):
    
    def __init__(self,template):
        self.comment = ""
        self.output = ""
        self.dirty = 1
        self.tmpFiles = []
        self.template = template

    def addLine(self,docLine):
        # Check to see if the docLine is a valid string
        if (docLine == '\n'):
            docLine = "<br/><br/>"
        self.comment+=" "+docLine
        self.dirty = 1

    def evaluateBlock(self):
        # Parse the comment into an appropriate HTML structure
        if (self.comment == ""):
            return
        self.output = self.template.replace('{R_insert}',self.comment)
        self.dirty = 0

    def toString(self):
        if (self.dirty):
            self.evaluateBlock()
        return self.output
